package com.chance.cc.crawler.development.scripts.autohome.video;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpConstant;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequest;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.CategoryTag;
import com.chance.cc.crawler.core.tags.KVTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AutoVMCommonField.*;

/**
 * @author lt
 * @version 1.0
 * @date 2020-11-23 14:04:42
 * @email okprog@sina.com
 */
public class AutoHomeVideoCrawlerScript extends CrawlerCommonScript {

    private Logger logger = LoggerFactory.getLogger(AutoHomeVideoCrawlerScript.class);

    private static final String scriptSite = "video";
    private static final String VIDEO_BASE_URL = "https://v.autohome.com.cn";
    private static final String BASE_URL = "https://www.autohome.com.cn/";

    private static final String videoUrlFormat = "https://v.autohome.com.cn/v-%s.html";
    private static final String listUrlFormat = "https://v.autohome.com.cn/pagedata?pagetype=2&ordertype=1&userid=%s&pageindex=%s";
    private static final String commentUrlFormat = "https://reply.autohome.com.cn/api/comments/show.json?count=50&appid=4&replydata=1&order=0&page=%s&id=%s";
    private static final String brandUrlFormat = "https://cloud-spec-infobyspeclist.xapi.autohome.com.cn/v1/carprice/series_infobyseriesid.ashx?_appid=ad&seriesid=%s";
    private static final String likesUrlFormat = "https://reply.autohome.com.cn/api/like/getcount.json?_appid=v&appid=4&liketype=1&objid=%s";
    private static final String seriesVideoListFormat = "https://v.m.autohome.com.cn/series/moredata?seriesid=%s&pageid=%s";


    private static final String indexRegex = "https?://v\\.autohome\\.com\\.cn/";
    private static final String listRegex = "https://v\\.autohome\\.com\\.cn/pagedata\\?pagetype=2&ordertype=1&userid=\\d*&pageindex=\\d*";
    private static final String videoRegex = "https?://v\\.autohome\\.com\\.cn/v-\\d*\\.html";
    private static final String commentRegex = "https://reply\\.autohome\\.com\\.cn/api/comments/show\\.json\\?count=50&appid=4&replydata=1&order=0&page=\\d*&id=\\d*";
    private static final String brandRegex = "https://cloud-spec-infobyspeclist\\.xapi\\.autohome\\.com\\.cn/v1/carprice/series_infobyseriesid\\.ashx\\?_appid=ad&seriesid=\\d*";
    private static final String likesUrlRegex = "https://reply\\.autohome\\.com\\.cn/api/like/getcount\\.json\\S*";
    private static final String seriesVideoListRegex = "https://v\\.m\\.autohome\\.com\\.cn/series/moredata\\S*";
    private static final String keysRegex = "https?://\\S*v1/meta/autohome/keys\\S*";


    private static final long ONE_SECOND = 1000L;
    private static final long ONE_MINUTE = 60000L;
    private static final long ONE_HOUR = 3600000L;
    private static final long ONE_DAY = 86400000L;

    @Override
    public String domain() {
        return "autohome";
    }

    @Override
    public void initUrlRegulars() {
        addUrlRegular(indexRegex);
        addUrlRegular(listRegex);
        addUrlRegular(videoRegex);
        addUrlRegular(commentRegex);
        addUrlRegular(brandRegex);
        addUrlRegular(keysRegex);
        addUrlRegular(seriesVideoListRegex);
    }

    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        CategoryTag categoryTag = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag();
        String crawlerSite = categoryTag.getKVTagStrVal("site");
        return crawlerSite.equalsIgnoreCase(scriptSite);
    }

    @Override
    public List<CrawlerRecord> prepareRequest(CrawlerRequestRecord requestRecord, List<CrawlerRequestRecord> supportSourceRecords) {
        HttpRequest httpRequest = requestRecord.getHttpRequest();
        List<CrawlerRecord> allItemRecords = new ArrayList<>();
        if (supportSourceRecords == null || supportSourceRecords.size() < 1) {
            return super.prepareRequest(requestRecord, supportSourceRecords);
        }
        CrawlerRequestRecord keywordRecord = null;
        for (CrawlerRequestRecord supportSourceRecord : supportSourceRecords) {
            if (supportSourceRecord.getHttpRequest().getUrl().matches(keysRegex)) {
                keywordRecord = supportSourceRecord;
            }
        }
        if (null == keywordRecord) {
            return super.prepareRequest(requestRecord, supportSourceRecords);
        }
        String keywordUrl = keywordRecord.getHttpRequest().getUrl();
        if (keywordUrl.matches(keysRegex)) {
            initKeywordsRecord(requestRecord, allItemRecords, keywordRecord);
        }
        if (allItemRecords.isEmpty()) {
            return super.prepareRequest(requestRecord, supportSourceRecords);
        }
        return allItemRecords;
    }

    private void initKeywordsRecord(CrawlerRequestRecord requestRecord, List<CrawlerRecord> allItemRecords, CrawlerRequestRecord keywordRecord) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(keywordRecord.getInternalDownloadPage().getRawText());
            if (jsonObject.getIntValue("status") == 0) {
                JSONArray contents = jsonObject.getJSONArray("content");
                for (Object content : contents) {
                    String keyword = ((JSONObject) content).getString("keyword");
                    String seriesVideoUrl = String.format(seriesVideoListFormat, keyword,"");
                    CrawlerRequestRecord crawlerRequestRecord = CrawlerRequestRecord.builder()
                            .turnPageRequest(requestRecord)
                            .httpUrl(seriesVideoUrl)
                            .recordKey(seriesVideoUrl)
                            .httpHead("user-agent","Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1")
                            .httpHead("referer",String.format("https://v.m.autohome.com.cn/%s/",keyword))
                            .releaseTime(System.currentTimeMillis())
                            .needWashed(false)
                            .needParsed(true)
                            .notFilterRecord()
                            .copyBizTags()
                            .build();
                    crawlerRequestRecord.getHttpRequest().setMethod(HttpConstant.Method.GET);
                    crawlerRequestRecord.tagsCreator().bizTags().addCustomKV("seriesId",keyword);
                    allItemRecords.add(crawlerRequestRecord);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<>();
        HttpRequest lastRequest = crawlerRequestRecord.getHttpRequest();
        int statusCode = httpPage.getStatusCode();
        String lastRequestUrl = lastRequest.getUrl();
        if (StringUtils.isBlank(httpPage.getRawText()) || !httpPage.isDownloadSuccess() || (statusCode != 200 && statusCode != 404)){
            parsedLinks.add(crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            crawlerRequestRecord.tagsCreator().requestTags().removeRequestType(CrawlerEnum.CrawlerRequestType.filter);
            return parsedLinks;
        }
        if (statusCode == 404){
            logger.error("页面不存在：" + statusCode);
            return parsedLinks;
        }
        CrawlerBusinessTags bizTags = crawlerRequestRecord.tagsCreator().bizTags();
        if (lastRequestUrl.matches(indexRegex)){
            return parseIndexLinks(crawlerRequestRecord, httpPage, parsedLinks);
        }
        if (lastRequestUrl.matches(listRegex)){
            return parseListLinks(crawlerRequestRecord, httpPage, parsedLinks, lastRequest, lastRequestUrl);
        }
        //车系视频列表
        if (lastRequestUrl.matches(seriesVideoListRegex)){
            return parseSeriesVideoLinks(crawlerRequestRecord,httpPage,parsedLinks);
        }
        if (lastRequestUrl.matches(videoRegex)){
            return parseVideoLinks(crawlerRequestRecord, httpPage, parsedLinks, lastRequest);
        }
        if (lastRequestUrl.matches(commentRegex)){
            return parseCommentLinks(crawlerRequestRecord, httpPage, parsedLinks, lastRequest);
        }
        return null;
    }

    private List<CrawlerRequestRecord> parseSeriesVideoLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        HttpRequest httpRequest = crawlerRequestRecord.getHttpRequest();
        String httpRequestUrl = httpRequest.getUrl();
        String seriesId = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("seriesId");
        try{
            JSONObject pageObj = JSONObject.parseObject(httpPage.getRawText());
            boolean hasMore = pageObj.getBooleanValue("hasmore");
            JSONArray items = pageObj.getJSONArray("items");
            if (hasMore){
                Map<String, Object> urlParams = getUrlParams(httpRequestUrl);
                if (null == urlParams){
                    logger.error("{} series video list url pars params error: [{}]",domain(),httpRequestUrl);
                    return parsedLinks;
                }
                String pageId = (String) urlParams.get("pageid");
                String nextPageId = "";
                if (StringUtils.isBlank(pageId)){
                    nextPageId = "21";
                }else {
                    nextPageId = String.valueOf(Integer.parseInt(pageId) + 20);
                }
                String nextPageUrl = String.format(seriesVideoListFormat,seriesId,nextPageId);
                CrawlerRequestRecord nextPageRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(crawlerRequestRecord)
                        .httpUrl(nextPageUrl)
                        .recordKey(nextPageUrl)
                        .httpHeads(httpRequest.getHeaders())
                        .copyBizTags()
                        .releaseTime(System.currentTimeMillis())
                        .build();
                if (isAllSkip(items)){
                    nextPageRecord.tagsCreator().requestTags().removeRequestType(CrawlerEnum.CrawlerRequestType.filter);
                }
                parsedLinks.add(nextPageRecord);
            }
            for (Object item : items) {
                JSONObject itemObj = (JSONObject)item;
                Map<String,Object> extraEach = new HashMap<>();
                String url = itemObj.getString("sharedaddress");
                if (!url.matches(videoRegex)){
                    continue;
                }
                String title = itemObj.getString("title");
                String videoId = itemObj.getString("id");
                String views = itemObj.getString("viewcount");
                String comments = itemObj.getString("replycount");
                String pubTime = itemObj.getString("publishtime");
                String itemUrl = String.format(videoUrlFormat,videoId);
                extraEach.put("itemUrl",itemUrl);
                extraEach.put("articleKey",videoId);
                extraEach.put("title",title);
                extraEach.put("views",views);
                extraEach.put("comments",comments);
                extraEach.put("listUrl",String.format("https://car.autohome.com.cn/video/series-%s.html",seriesId));
                try {
                    CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(itemUrl)
                            .httpUrl(itemUrl)
                            .releaseTime(DateUtils.parseDate(pubTime, "yyyy-MM-dd HH:mm:ss").getTime())
                            .resultLabelTag(article)
                            .resultLabelTag(interaction)
                            .copyBizTags()
                            .build();
                    itemRecord.getHttpRequest().setExtras(extraEach);
                    parsedLinks.add(itemRecord);
                } catch (Exception e) {
                    logger.error(e.getMessage(),"parse date error");
                }
            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return parsedLinks;
    }

    private boolean isAllSkip(JSONArray items) {
        for (Object item : items) {
            JSONObject itemObj = (JSONObject)item;
            String url = itemObj.getString("sharedaddress");
            if (url.matches(videoRegex)){
                return false;
            }
        }
        return true;
    }

    private List<CrawlerRequestRecord> parseCommentLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks, HttpRequest lastRequest) {
        try{
            httpPage.getJson().jsonPath($_type + ".commentlist").all();
            httpPage.getJson().jsonPath($_type + ".commentcountall").all();
            httpPage.getJson().jsonPath($_type + ".commentcount").all();
            httpPage.getJson().jsonPath($_type + ".page").all();
        }catch (Exception e){
            logger.error("comment url is download error!detail is [{}]",JSONObject.toJSONString(httpPage));
            parsedLinks.add(crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            crawlerRequestRecord.tagsCreator().requestTags().removeRequestType(CrawlerEnum.CrawlerRequestType.filter);
            return parsedLinks;
        }
        if(httpPage.getJson().jsonPath($_type + ".commentlist").all().size() < 1){
            logger.error("requestUrl is download is complete[{}]",JSONObject.toJSONString(httpPage));
        }
        //根据返回的json结果计算下一页
        crawlerRequestRecord.setNeedWashPage(true);
        Map<String, Object> extras = lastRequest.getExtras();
        String articleKey = (String) extras.get("articleKey");
        JSONObject jsonObject = JSONObject.parseObject(httpPage.getRawText());
        int currentPage = jsonObject.getIntValue("page");
        int commentCount = jsonObject.getIntValue("commentcount");
        int maxPage = (int) Math.ceil(commentCount / 50.0);
        if (currentPage < maxPage){
            String commentUrl = String.format(commentUrlFormat,(currentPage + 1), articleKey);
            CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .recordKey(commentUrl)
                    .httpUrl(commentUrl)
                    .releaseTime(crawlerRequestRecord.getReleaseTime())
                    .needWashed(true)
                    .resultLabelTag(comment)
                    .resultLabelTag(interaction)
                    .copyBizTags()
                    .build();
            commentRecord.getHttpRequest().setExtras(copyExtras(extras));
            parsedLinks.add(commentRecord);
        }
        return parsedLinks;
    }

    private List<CrawlerRequestRecord> parseVideoLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks, HttpRequest lastRequest) {
        if (httpPage.getRawText().contains("尊敬的用户您好，您的访问出现异常，为确认本次访问为正常用户行为")){
            parsedLinks.add(crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            crawlerRequestRecord.tagsCreator().requestTags().removeRequestType(CrawlerEnum.CrawlerRequestType.filter);
            return parsedLinks;
        }
        crawlerRequestRecord.setNeedWashPage(true);
        Map<String, Object> extras = lastRequest.getExtras();
        //生成内循环获取车系
        String seriesId = httpPage.getHtml().xpath("//div[@id=\"auto-brand-vr\"]/iframe/@data-seriesid").get();
        String brandUrl = String.format(brandUrlFormat,seriesId);
        CrawlerRequestRecord brandRecord = CrawlerRequestRecord.builder()
                .itemPageRequest(crawlerRequestRecord)
                .recordKey(brandUrl)
                .httpUrl(brandUrl)
                .releaseTime(crawlerRequestRecord.getReleaseTime())
                .requestLabelTag(CrawlerEnum.CrawlerRequestType.internalDownload)
                .needParsed(false)
                .build();
        brandRecord.getHttpRequest().setExtras(copyExtras(extras));
        parsedLinks.add(brandRecord);

        //生成内循环获取点赞
        String articleKey = (String) extras.get("articleKey");
        String likesUrl = String.format(likesUrlFormat,articleKey);
        CrawlerRequestRecord likesRecord = CrawlerRequestRecord.builder()
                .itemPageRequest(crawlerRequestRecord)
                .recordKey(likesUrl)
                .httpUrl(likesUrl)
                .releaseTime(crawlerRequestRecord.getReleaseTime())
                .requestLabelTag(CrawlerEnum.CrawlerRequestType.internalDownload)
                .needParsed(false)
                .build();
        likesRecord.getHttpRequest().setExtras(copyExtras(extras));
        parsedLinks.add(likesRecord);
        CategoryTag categoryTag = crawlerRequestRecord.tagsCreator().scheduleTags().getCategoryTag();
        if (categoryTag.getLabelTag(CrawlerEnum.CrawlerDataType.comment.enumVal()) != null) {
            if (!crawlerRequestRecord.tagsCreator().bizTags().hasKVTag("comment_record_filter_info")) {
                logger.error("{} crawler comment need to filter information!",domain());
                return parsedLinks;
            }
            KVTag filterInfoTag = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTag("comment_record_filter_info");
            CrawlerRecord filterInfoRecord = JSON.parseObject((String) filterInfoTag.getVal(), CrawlerRecord.class);
            //生成外循环评论链接
            String commentUrl = String.format(commentUrlFormat,1,extras.get("articleKey"));
            CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(commentUrl)
                    .releaseTime(System.currentTimeMillis())
                    .notFilterRecord()
                    .needWashed(true)
                    .resultLabelTag(comment)
                    .resultLabelTag(interaction)
                    .copyBizTags()
                    .build();
            commentRecord.setFilter(filterInfoRecord.getFilter());
            commentRecord.setFilterInfos(filterInfoRecord.getFilterInfos());
            commentRecord.getHttpRequest().setExtras(copyExtras(extras));
            parsedLinks.add(commentRecord);
        }

        return parsedLinks;
    }

    private List<CrawlerRequestRecord> parseListLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks, HttpRequest lastRequest, String lastRequestUrl) {
        //翻页
        Map<String, Object> extras = lastRequest.getExtras();
        int currentPage = Integer.parseInt(lastRequestUrl.split("pageindex=")[1]);
        String nextPageUrl = String.format(listUrlFormat,extras.get("listUid"),(currentPage + 1));
        if (StringUtils.isNotBlank(nextPageUrl)){
            CrawlerRequestRecord turnPageRequest = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .recordKey(nextPageUrl)
                    .httpUrl(nextPageUrl)
                    .releaseTime(System.currentTimeMillis())
                    .copyBizTags()
                    .build();

            turnPageRequest.getHttpRequest().setExtras(extras);
            parsedLinks.add(turnPageRequest);
        }
        //列表
        List<Selectable> selectables = httpPage.getHtml().xpath("//ul[@class=\"channel-list active\"]/li").nodes();
        for (Selectable selectable : selectables) {
            Map<String,Object> extraEach = copyExtras(extras);
            String itemUrl = VIDEO_BASE_URL + selectable.xpath("./div[@class=\"con\"]/a/@href").get();
            String articleKey = itemUrl.substring(itemUrl.lastIndexOf("-") + 1).split("\\.")[0];
            String title = selectable.xpath(".//p[@class=\"tit\"]/a/text()").get();
            String pubTime = selectable.xpath("./div[@class=\"info\"]/span[@class=\"athm-right\"]/text()").get();
            String views = selectable.xpath("./div[@class=\"info\"]/div[@class=\"athm-left\"]/span[@class=\"video-icon\"]/text()").all().get(1).trim();
            String comments = selectable.xpath("./div[@class=\"info\"]/div[@class=\"athm-left\"]/span[@class=\"comment\"]/text()").all().get(1).trim();
            extraEach.put("itemUrl",itemUrl);
            extraEach.put("articleKey",articleKey);
            extraEach.put("title",title);
            extraEach.put("views",views);
            extraEach.put("comments",comments);
            extraEach.put("listUrl",lastRequestUrl);
            try {
                CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .recordKey(itemUrl)
                        .httpUrl(itemUrl)
                        .releaseTime(cleanTime(pubTime, "yyyy-MM-dd"))
                        .resultLabelTag(article)
                        .resultLabelTag(interaction)
                        .copyBizTags()
                        .build();
                itemRecord.getHttpRequest().setExtras(extraEach);
                parsedLinks.add(itemRecord);
            } catch (ParseException e) {
                logger.error(e.getMessage(),"parse date error");
            }
        }
        return parsedLinks;
    }

    private List<CrawlerRequestRecord> parseIndexLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        List<Selectable> listNodes = httpPage.getHtml().xpath("//ul[@class=\"athm-tab channel-tab\"]/li/a").nodes();
        for (Selectable listNode : listNodes) {
            String url = listNode.xpath("./@href").get();
            if (url.startsWith("/u")){
                String uid = url.split("u/")[1].split("/#")[0];
                String listUrl = String.format(listUrlFormat,uid,1);
                String listTag = listNode.xpath("./text()").get();

                Map<String,Object> extras = new HashMap<>();
                extras.put("listUid",uid);

                CrawlerRequestRecord listRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(crawlerRequestRecord)
                        .httpUrl(listUrl)
                        .recordKey(listUrl)
                        .releaseTime(System.currentTimeMillis())
                        .copyBizTags()
                        .notFilterRecord()
                        .build();
                List<String> path = new ArrayList<>();
                path.add(listTag);
                listRecord.tagsCreator().bizTags().addCustomKV(Field_Path,path);
                listRecord.getHttpRequest().setExtras(extras);
                parsedLinks.add(listRecord);
            }
        }
        return parsedLinks;
    }

    @Override
    public void afterInternalDownload(CrawlerRequestRecord crawlerRecord, List<CrawlerRequestRecord> internalDownloadRecords, List<CrawlerRequestRecord> links) {
        HttpRequest lastRequest = crawlerRecord.getHttpRequest();
        Map<String, Object> extras = lastRequest.getExtras();
        for (CrawlerRequestRecord internalDownloadRecord : internalDownloadRecords) {
            String internalUrl = internalDownloadRecord.getHttpRequest().getUrl();
            if (!internalDownloadRecord.getInternalDownloadPage().isDownloadSuccess()){
                crawlerRecord.setNeedWashPage(false);
                crawlerRecord.setNeedParsedPage(false);
                CrawlerRequestRecord newRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRecord)
                        .httpUrl(crawlerRecord.getHttpRequest().getUrl())
                        .recordKey(crawlerRecord.getHttpRequest().getUrl())
                        .releaseTime(crawlerRecord.getReleaseTime())
                        .copyBizTags()
                        .needParsed(true)
                        .needWashed(true)
                        .notFilterRecord()
                        .build();
                newRecord.getHttpRequest().setExtras(extras);
                links.add(newRecord);
            }
            else if (internalUrl.matches(brandRegex)){
                JSONObject jsonObject = JSONObject.parseObject(internalDownloadRecord.getInternalDownloadPage().getRawText());
                if (0 == jsonObject.getIntValue("returncode")){
                    jsonObject = jsonObject.getJSONObject("result");
                    String brand = jsonObject.getString("brandname");
                    String seriesName = jsonObject.getString("seriesname");
                    String seriesId = jsonObject.getString("seriesid");
                    String seriesUrl = BASE_URL + seriesId;
                    extras.put("brand",brand);
                    extras.put("seriesName",seriesName);
                    extras.put("seriesUrl",seriesUrl);
                    extras.put("seriesId",seriesId);
                }else {
                    logger.warn("get data failed from :" + lastRequest.getUrl());
                }

            }
            else if (internalUrl.matches(likesUrlRegex)) {
                JSONObject jsonObject = JSONObject.parseObject(internalDownloadRecord.getInternalDownloadPage().getRawText());
                if (0 == jsonObject.getIntValue("returncode")) {
                    jsonObject = jsonObject.getJSONObject("result");
                    String likes = jsonObject.getString("count");
                    extras.put("likes",likes);
                }else {
                    extras.put("likes","0");
                }
            }
        }
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        if (crawlerRequestRecord.tagsCreator().resultTags().hasDataType(article)){
            crawlerDataList.addAll(washArticle(crawlerRequestRecord, httpPage));
        }

        if (crawlerRequestRecord.tagsCreator().resultTags().hasDataType(interaction)){
            crawlerDataList.addAll(washInteraction(crawlerRequestRecord,httpPage));
        }

        if (crawlerRequestRecord.tagsCreator().resultTags().hasDataType(comment)){
            crawlerDataList.addAll(washComment(crawlerRequestRecord,httpPage));
        }

        return crawlerDataList;
    }

    private List<CrawlerData> washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerArticleDataList = new ArrayList<>();
        HttpRequest lastRequest = crawlerRequestRecord.getHttpRequest();
        Map<String, Object> extras = lastRequest.getExtras();
        String content = httpPage.getHtml().xpath("//div[@class=\"video-msg\"]/div/p[1]/span/text()").get();
        content = content.replaceAll("&\\S*?;","").replaceAll("\n","").replaceAll("\\wdquo;","").trim();

        String author = httpPage.getHtml().xpath("//div[@class=\"video-channel\"]/a[2]/text()").get();

        String authorUrl = httpPage.getHtml().xpath("//div[@class=\"video-channel\"]/a[2]/@href").get();
        String authorId = "";
        if (StringUtils.isNotBlank(authorUrl)){
            authorId = authorUrl.split("u/")[1].split("#")[0];
        }

        String follows = httpPage.getHtml().xpath("//span[@id=\"fans\"]/text()").get().split(" ")[0];
        if (follows.contains("万")){
            follows = follows.replace("万","");
            if (follows.contains(".")){
                follows = follows.replace(".","") + "000";
            }else {
                follows = follows + "0000";
            }
        }
        String audioUrl = httpPage.getHtml().xpath("//video[@class=\"ahvp__video__setup\"]/@src").get();
        String title = (String)extras.get("title");
        title = title.replaceAll("&\\S*?;","").replaceAll("\n","").replaceAll("\\wdquo;","").trim();
        String articleKey = (String)extras.get("articleKey");
        String brand = (String)extras.get("brand");
        String seriesName = (String)extras.get("seriesName");
        String seriesUrl = (String)extras.get("seriesUrl");
        String seriesId = (String)extras.get("seriesId");
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        CrawlerData crawlerData = CrawlerData.builder()
                .data(crawlerRequestRecord, httpPage)
                .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, article.enumVal(), articleKey))
                .url(lastRequest.getUrl())
                .releaseTime(crawlerRequestRecord.getReleaseTime())
                .addContentKV(Field_Title,title)
                .addContentKV(Field_Content,content)
                .addContentKV(Field_Author,author)
                .addContentKV(Field_Author_Id,authorId)
                .addContentKV(Field_Author_Follows,follows)
                .addContentKV(Field_Urls, (String) extras.get("listUrl"))
                .addContentKV(Field_Audios,audioUrl)
                .resultLabelTag(article)
                .build();
        if (StringUtils.isNotBlank(seriesName)){
            List<Map<String,String>> seriesList = new ArrayList<>();
            Map<String, String> seriesInfo = new HashMap<>();
            seriesInfo.put("series_name",seriesName);
            seriesInfo.put("series_url",seriesUrl);
            seriesInfo.put("series_id",seriesId);
            seriesList.add(seriesInfo);
            crawlerData.tagsCreator().bizTags().addCustomKV(Tag_Field_Series,seriesList);
            crawlerData.tagsCreator().bizTags().addCustomKV(Tag_Field_Brand,brand);
        }

        crawlerArticleDataList.add(crawlerData);
        return crawlerArticleDataList;
    }

    private List<CrawlerData> washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerInteractionDataList = new ArrayList<>();
        HttpRequest lastRequest = crawlerRequestRecord.getHttpRequest();
        String lastRequestUrl = lastRequest.getUrl();
        Map<String, Object> extras = lastRequest.getExtras();
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        if (lastRequestUrl.matches(videoRegex)){
            String articleKey = (String)extras.get("articleKey");
            String views = (String)extras.get("views");
            if (views.contains("万")){
                views = views.replace("万","");
                if (views.contains(".")){
                    views = views.replace(".","") + "000";
                }else {
                    views = views + "0000";
                }
            }
            String likes = (String) extras.get("likes");
            String comments = (String)extras.get("comments");
            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, interaction.enumVal(), articleKey))
                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, article.enumVal(), articleKey))
                    .url(lastRequestUrl)
                    .releaseTime(crawlerRequestRecord.getReleaseTime())
                    .addContentKV(Field_I_Comments,String.valueOf(comments))
                    .addContentKV(Field_I_Views,views)
                    .addContentKV(Field_I_Likes,likes)
                    .resultLabelTag(interaction)
                    .build();
            crawlerInteractionDataList.add(crawlerData);
        }
        if (lastRequestUrl.matches(commentRegex)){
            JSONObject jsonObject = JSONObject.parseObject(httpPage.getRawText());
            JSONArray commentList = jsonObject.getJSONArray("commentlist");
            for (Object o : commentList) {
                JSONObject commentJson = (JSONObject)o;
                String commentId = commentJson.getString("ReplyId");
                String likes = commentJson.getString("RUp");
                String pubTime = commentJson.getString("RReplyDate");
                pubTime = pubTime.split("\\(")[1];
                if (pubTime.contains("+")){
                    pubTime = pubTime.split("\\+")[0];
                }
                if (pubTime.contains("-")){
                    pubTime = pubTime.split("-")[0];
                }
                try {
                    CrawlerData crawlerData = CrawlerData.builder()
                            .data(crawlerRequestRecord, httpPage)
                            .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, interaction.enumVal(), commentId))
                            .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, comment.enumVal(), commentId))
                            .url((String) extras.get("itemUrl"))
                            .releaseTime(new Long(pubTime))
                            .addContentKV(Field_I_Likes,likes)
                            .resultLabelTag(interaction)
                            .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                            .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                            .build();
                    crawlerInteractionDataList.add(crawlerData);
                } catch (Exception e) {
                    logger.error(e.getMessage(),"parse date error");
                }
            }
        }
        return crawlerInteractionDataList;
    }

    private List<CrawlerData> washComment(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerCommentDataList = new ArrayList<>();
        HttpRequest lastRequest = crawlerRequestRecord.getHttpRequest();
        Map<String, Object> extras = lastRequest.getExtras();
        JSONObject jsonObject = JSONObject.parseObject(httpPage.getRawText());
        JSONArray commentList = jsonObject.getJSONArray("commentlist");
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");

        for (Object o : commentList) {
            JSONObject commentJson = (JSONObject)o;
            String commentId = commentJson.getString("ReplyId");
            String pubTime = commentJson.getString("RReplyDate");
            String author = commentJson.getString("RMemberName");
            String authorId = commentJson.getString("RMemberId");
            String content = commentJson.getString("RContent");
            String floor = commentJson.getString("RFloor");
            pubTime = pubTime.split("\\(")[1];
            if (pubTime.contains("+")){
                pubTime = pubTime.split("\\+")[0];
            }
            if (pubTime.contains("-")){
                pubTime = pubTime.split("-")[0];
            }
            try {
                CrawlerData crawlerCommentData = CrawlerData.builder()
                        .data(crawlerRequestRecord, httpPage)
                        .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, comment.enumVal(), commentId))
                        .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, article.enumVal(), extras.get("articleKey")))
                        .url((String) extras.get("itemUrl"))
                        .releaseTime(new Long(pubTime))
                        .addContentKV(Field_Author,author)
                        .addContentKV(Field_Author_Id,authorId)
                        .addContentKV(Field_Content,content)
                        .addContentKV(Field_Floor,floor)
                        .resultLabelTag(comment)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                        .build();
                crawlerCommentDataList.add(crawlerCommentData);
            } catch (Exception e) {
                logger.error(e.getMessage(),"parse date error");
            }
        }
        return crawlerCommentDataList;
    }


    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    private long cleanTime(String timeStr,String pattern) throws ParseException {
        if (timeStr.contains("发布")){
            timeStr = timeStr.split("：")[1];
        }
        if (timeStr.contains("刚刚")){
            return System.currentTimeMillis();
        }else if (timeStr.contains("前")){
            return timeBefore(timeStr);
        }else if (timeStr.contains("-")){
            return DateUtils.parseDate(timeStr,pattern).getTime();
        }else {
            return 0;
        }

    }

    private long timeBefore(String timeStr) {
        if (timeStr.matches("\\d*天前")){
            int timeNum = Integer.parseInt(timeStr.split("天")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_DAY);

        }else if (timeStr.matches("\\d*秒前")){
            int timeNum = Integer.parseInt(timeStr.split("秒")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_SECOND);

        }else if (timeStr.matches("\\d*分钟前")){
            int timeNum = Integer.parseInt(timeStr.split("分钟")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_MINUTE);

        }else if (timeStr.matches("\\d*分钟\\d*秒前")) {
            String[] split = timeStr.split("分钟");
            int minutes = Integer.parseInt(split[0]);
            int seconds = Integer.parseInt(split[1].split("秒")[0]);
            long times = (minutes * ONE_MINUTE) + (seconds * ONE_SECOND);
            return System.currentTimeMillis() - times;

        }else if (timeStr.matches("\\d*小时前")){
            int timeNum = Integer.parseInt(timeStr.split("小时")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_HOUR);

        }else if (timeStr.matches("\\d*小时\\d*分钟前")){
            String[] split = timeStr.split("小时");
            int hours = Integer.parseInt(split[0]);
            int minutes = Integer.parseInt(split[1].split("分钟")[0]);
            long times = (hours * ONE_HOUR) + (minutes * ONE_MINUTE);
            return System.currentTimeMillis() - times;

        }else if (timeStr.matches("\\d*周前")){
            int timeNum = Integer.parseInt(timeStr.split("周")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_DAY * 7);

        }else if (timeStr.matches("\\d*个月前")){
            int timeNum = Integer.parseInt(timeStr.split("个")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_DAY * 31);
        }else {
            return 0;

        }
    }

    public static Map<String, Object> copyExtras(Map<String,Object> inExtras){
        Map<String,Object> extras = new HashMap<>();
        for (Map.Entry<String, Object> entry : inExtras.entrySet()) {
            extras.put(entry.getKey(),entry.getValue());
        }
        return extras;
    }

    private static List<String> agentList = new ArrayList<>();

    static {
        agentList.add("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko");
        agentList.add("Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 7.0; InfoPath.3; .NET CLR 3.1.40767; Trident/6.0; en-IN)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/4.0; InfoPath.2; SV1; .NET CLR 2.0.50727; WOW64)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)");
        agentList.add("Mozilla/4.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)");
        agentList.add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2");
        agentList.add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/525.28.3");
        agentList.add("Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16");
        agentList.add("Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14");
        agentList.add("Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14");
        agentList.add("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0) Opera 12.14");
        agentList.add("Opera/12.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.02");
        agentList.add("Opera/9.80 (Windows NT 6.1; U; es-ES) Presto/2.9.181 Version/12.00");
        agentList.add("Opera/9.80 (Windows NT 5.1; U; zh-sg) Presto/2.9.181 Version/12.00");
        agentList.add("Opera/12.0(Windows NT 5.2;U;en)Presto/22.9.168 Version/12.00");
        agentList.add("Opera/12.0(Windows NT 5.1;U;en)Presto/22.9.168 Version/12.00");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1");
        agentList.add("Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0");
        agentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0");
        agentList.add("Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.13 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3756.400 QQBrowser/10.5.4043.400");
    }

    private static String getRandomUA() {
        return agentList.get(RandomUtils.nextInt(0, agentList.size() - 1));
    }

    /**
     * 将url参数转换成map
     *
     * @param url http://*.*.com?aa=11&bb=22&cc=33
     * @return map
     */
    private Map<String, Object> getUrlParams(String url) {
        Map<String, Object> map = new HashMap<String, Object>(0);
        String param = null;
        if (url.contains("?")) {
            param = url.split("\\?")[1];
        }
        if (StringUtils.isBlank(param)) {
            return null;
        }
        String[] params = param.split("&");
        for (String s : params) {
            String[] p = s.split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }

}
